<template>
  <el-scrollbar height="600px" style="margin-top: 10px">
    <el-space wrap>
      <el-card
        v-for="cardItem in cardData"
        :key="cardItem.tableNo"
        class="box-card"
      >
        <template #header>
          <div class="card-header">
            <span>{{
              cardItem.tableNo +
              "-" +
              cardItem.name +
              "  " +
              (cardItem.status == 0 ? "空闲" : "使用中")
            }}</span>
            <el-dropdown>
              <el-button type="primary"
                >操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    :icon="CirclePlus"
                    @click="handleBeginTime(cardItem)"
                    >开始计时</el-dropdown-item
                  >
                  <el-dropdown-item
                    :icon="CirclePlus"
                    @click="handleSettlement(cardItem)"
                    >结算</el-dropdown-item
                  >
                  <el-dropdown-item
                    :icon="CirclePlus"
                    @click="handleDetail(cardItem)"
                    >详情</el-dropdown-item
                  >
                  <el-dropdown-item
                    :icon="CirclePlus"
                    @click="handleAddGoods(cardItem)"
                    >添加商品</el-dropdown-item
                  >
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </template>

        <div class="text item">
          开始计费时间:
          {{
            cardItem.status == 1 && cardItem.lastBeginTime != null
              ? utils.formatDate(cardItem.lastBeginTime)
              : ""
          }}
        </div>
        <div class="text item">计费时长: {{ cardItem.totalTime }}</div>
        <div class="text item">单价: {{ cardItem.unitPrice + "元 / 时" }}</div>
        <div class="text item">总消费: {{ cardItem.totalFee }}</div>
      </el-card>
    </el-space>
  </el-scrollbar>

  <el-dialog v-model="dialogFormVisible" destroy-on-close title="添加商品">
    <el-form ref="formRef" :model="form">
      <el-form-item label="商品编码" :label-width="formLabelWidth">
        <el-select
          v-model="form.goodsCode"
          placeholder="请选择商品编码"
          filterable
          clearable
          reserve-keyword
          @clear="selectClear"
          :loading="loading"
        >
          <el-option
            v-for="item in options"
            @click.native="selectChange(item)"
            :key="item.code"
            :label="item.code + ' - ' + item.name"
            :value="item.code"
          >
            <span style="float: left">{{ item.code }}</span>
            <span style="float: right; font-size: 13px">{{ item.name }}</span>
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="商品名称" :label-width="formLabelWidth">
        <el-input
          readonly
          disabled
          v-model="form.goodsName"
          placeholder="只读"
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item label="单价" :label-width="formLabelWidth">
        <el-input-number
          type="number"
          readonly
          disabled
          v-model="form.goodsPrice"
          min="0"
          maxlength="18"
          placeholder="只读"
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item label="单位" :label-width="formLabelWidth">
        <el-input
          readonly
          disabled
          v-model="form.goodsUnit"
          maxlength="128"
          placeholder="只读"
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item label="数量" :label-width="formLabelWidth">
        <el-input-number
          @change="countChange"
          v-model="form.goodsCount"
          maxlength="128"
          min="1"
          placeholder="数量"
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item label="支付状态" :label-width="formLabelWidth">
        <el-select
          v-model="form.payStatus"
          class="m-2"
          placeholder="请选择支付状态"
        >
          <el-option
            v-for="item in payStatusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="支付时间" :label-width="formLabelWidth">
        <el-date-picker
          v-model="form.payTime"
          type="datetime"
          placeholder="请输入结算时间"
        />
      </el-form-item>
      <el-form-item label="支付金额" :label-width="formLabelWidth">
        <el-input-number
          placeholder="请输入支付金额"
          min="0"
          v-model="form.actuallyPaidAmount"
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item label="id" :label-width="formLabelWidth" v-show="false">
        <el-input v-model="form.idSalesRecord" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="saveGoods"> 确认 </el-button>
      </span>
    </template>
  </el-dialog>

  <el-drawer
    v-model="drawer"
    title=""
    size="100%"
    :show-close="false"
    :direction="direction"
  >
    <template #header="{ close, titleId, titleClass }">
      <h4 :id="titleId" :class="titleClass">结算/详情</h4>
      <el-button v-if="showJieSuabtn" type="success" @click="handleJieSuan">
        <el-icon class="el-icon--left"><Money /></el-icon>
        结算
      </el-button>
      <el-button type="danger" @click="close">
        <el-icon class="el-icon--left"><CircleCloseFilled /></el-icon>
        关闭
      </el-button>
    </template>

    <el-scrollbar height="100%">
      <el-descriptions border title="">
        <el-descriptions-item label="开始计费时间">{{
          utils.formatDate(feeDescriptions.beginTime)
        }}</el-descriptions-item>
        <el-descriptions-item label="牌桌使用时长">{{
          feeDescriptions.totalTime
        }}</el-descriptions-item>
        <el-descriptions-item label="牌桌单价（元 / 时）">{{
          feeDescriptions.unitPrice
        }}</el-descriptions-item>
        <el-descriptions-item label="牌桌总计费金额">{{
          feeDescriptions.cardPaidAmount
        }}</el-descriptions-item>
        <el-descriptions-item label="商品已结算金额">{{
          feeDescriptions.goodsPaidAmount
        }}</el-descriptions-item>
        <el-descriptions-item label="商品未结算金额">{{
          feeDescriptions.goodsUnPaidAmount
        }}</el-descriptions-item>
        <el-descriptions-item label="应收金额">{{
          feeDescriptions.paidAmount
        }}</el-descriptions-item>
        <el-descriptions-item label="实收金额"
          ><el-input-number
            type="number"
            v-model="feeDescriptions.actuallyPaidAmount"
            min="0"
            maxlength="18"
            placeholder="实收金额"
            autocomplete="off"
          />
        </el-descriptions-item>
      </el-descriptions>

      <el-table :data="goodsSalesTableData" stripe border>
        <el-table-column prop="goodsCode" label="商品编码" />
        <el-table-column prop="goodsName" label="商品名称" />
        <el-table-column prop="goodsName" label="商品单价">
          <template #default="scope">
            {{ scope.row.goodsPrice + " 元 / " + scope.row.goodsUnit }}
          </template>
        </el-table-column>
        <el-table-column prop="goodsCount" label="销售数量" />
        <el-table-column prop="actuallyPaidAmount" label="实际收入金额(元)" />
        <el-table-column prop="payStatus" label="支付状态">
          <template #default="scope">
            {{ scope.row.payStatus == 0 ? "已支付" : "未支付" }}
          </template>
        </el-table-column>
        <el-table-column prop="payTime" label="结算时间">
          <template #default="scope">
            {{ utils.formatDate(scope.row.payTime) }}
          </template>
        </el-table-column>
      </el-table>
    </el-scrollbar>
  </el-drawer>
</template>

<script setup>
import dayjs from "dayjs";
import { ref, reactive } from "vue";
import { dbConnect } from "@/utils/sqlUtils.js";
import {
  Calendar,
  ArrowLeft,
  ArrowRight,
  Delete,
  Edit,
  CirclePlus,
  CircleCloseFilled,
  Money,
  ArrowDown,
  Share,
} from "@element-plus/icons-vue";
import * as utils from "@/utils/utils.js";
import { ElMessage, ElMessageBox } from "element-plus";

const dialogFormVisible = ref(false);
const tableData = reactive([]);
const formLabelWidth = "140px";
const formRef = ref({});
const drawer = ref(false);
const direction = ref("ttb");
const showJieSuabtn = ref(true);
const goodsSalesTableData = reactive([]);
const feeDescriptions = {};

const cardData = reactive([]);
const loading = ref(false);
const options = reactive([]);
let currentCardItem = {};
const payStatusOptions = [
  {
    value: 0,
    label: "已支付",
  },
  {
    value: 1,
    label: "未支付",
  },
];

const form = reactive({
  idSalesRecord: "",
  idGoods: 1,
  goodsCode: "",
  goodsName: "",
  goodsPrice: 0,
  goodsUnit: "",
  goodsCount: 1,
  goodsTotalAmount: "",
  payTime: new Date(),
  actuallyPaidAmount: 0,
  payStatus: 0,
  createTime: {},
  updateTime: {},
});

initData();

loadGoodsData();

function loadGoodsData() {
  dbConnect.all("select * from goods", (err, row) => {
    options.splice(0);
    options.push(...row);
  });
}

function selectChange(item) {
  form.goodsCode = item.code;
  form.goodsName = item.name;
  form.idGoods = item.idGoods;
  form.goodsPrice = item.price;
  form.goodsUnit = item.unit;
  form.actuallyPaidAmount = (form.goodsPrice * form.goodsCount).toFixed(2);
}

function selectClear() {
  form.goodsCode = null;
  form.goodsName = null;
  form.idGoods = null;
  form.goodsPrice = null;
  form.goodsUnit = null;
  form.actuallyPaidAmount = null;
}

function countChange() {
  form.actuallyPaidAmount = (form.goodsPrice * form.goodsCount).toFixed(2);
}

const timer = setInterval(() => {
  for (let item of cardData) {
    if (item.status == 1) {
      const beginTime = dayjs(utils.formatDate(item.lastBeginTime));
      const endDate = dayjs(new Date());
      const diffTime = endDate.diff(beginTime, "second");
      item.totalTime = utils.formatSecondsToMinuteHour(diffTime);
      let totalFee = ((item.unitPrice / (60 * 60)) * diffTime).toFixed(2);
      item.totalFee = totalFee == null ? 0 + " 元" : totalFee + " 元";
    }
  }
}, 1000);

function saveGoods() {
  let insertsql = `INSERT INTO sales_record (idGoods, goodsCode,goodsName,goodsPrice,goodsUnit,goodsCount,payTime,actuallyPaidAmount,updateTime,createTime, year,month,day,type,payStatus, payBatchNo) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);`;
  dbConnect
    .prepare(insertsql, [
      form.idGoods,
      form.goodsCode,
      form.goodsName,
      form.goodsPrice,
      form.goodsUnit,
      form.goodsCount,
      dayjs(form.payTime).toDate().getTime(),
      form.actuallyPaidAmount,
      new Date().getTime(),
      new Date().getTime(),
      utils.getYear(dayjs(form.payTime).toDate()),
      utils.getFullMonth(dayjs(form.payTime).toDate()),
      utils.getFullDay(dayjs(form.payTime).toDate()),
      1,
      form.payStatus,
      currentCardItem.payBatchNo,
    ])
    .run((err) => {
      if (err == null) {
        ElMessage({
          message: "新增成功",
          type: "success",
        });
        dialogFormVisible.value = false;
      } else {
        ElMessage.error("新增失败" + err);
      }
    });
}

function saveCardTableSales() {
  const beginTime = dayjs(utils.formatDate(currentCardItem.lastBeginTime));
  const endDate = dayjs(new Date());
  const diffTime = endDate.diff(beginTime, "second");
  currentCardItem.totalTime = utils.formatSecondsToMinuteHour(diffTime);
  let totalFee = ((currentCardItem.unitPrice / (60 * 60)) * diffTime).toFixed(
    2
  );
  let insertsql = `INSERT INTO sales_record (idBoardGameTable, bardGameCode, bardGameName,bardGameUnitPrice,boardGameBeginTime,boardGameEndTime,actuallyPaidAmount,updateTime,createTime,year,month,day,type,payTime, payStatus, payBatchNo) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);`;
  dbConnect
    .prepare(insertsql, [
      currentCardItem.idBoardGameTable,
      currentCardItem.tableNo,
      currentCardItem.name,
      currentCardItem.unitPrice,
      currentCardItem.lastBeginTime,
      new Date().getTime(),
      feeDescriptions.actuallyPaidAmount,
      new Date().getTime(),
      new Date().getTime(),
      utils.getYear(),
      utils.getFullMonth(),
      utils.getFullDay(),
      0,
      new Date().getTime(),
      0,
      currentCardItem.payBatchNo,
    ])
    .run((err) => {
      if (err != null) {
        ElMessage.error("结算失败" + err);
      }
    });

  let updateSql = `UPDATE board_game_table SET status=?, lastBeginTime=?, lastEndTime=?, updateTime=?, payBatchNo=? WHERE idBoardGameTable = ?`;
  dbConnect
    .prepare(updateSql, [
      0,
      null,
      new Date().getTime(),
      new Date().getTime(),
      null,
      currentCardItem.idBoardGameTable,
    ])
    .run((err) => {
      if (err != null) {
        ElMessage({
          showClose: true,
          message: "操作失败",
          type: "error",
        });
      }
    });
}

function initData() {
  dbConnect.all("select * from board_game_table", (err, row) => {
    if (err != null) {
      ElMessage({
        type: "error",
        message: "查询失败" + err,
      });
    }
    cardData.splice(0);
    cardData.push(...row);
  });
}

function handleBeginTime(cardItem) {
  if (cardItem.status != 0) {
    ElMessage({
      showClose: true,
      message: "计时已启动，请勿重复操作",
      type: "error",
    });
    return;
  }

  const nowDate = new Date();
  const payBatchNo =
    cardItem.tableNo + dayjs(nowDate).format("YYYYMMDDHHMMSSS");
  let updateSql = `UPDATE board_game_table SET status=?, lastBeginTime=?, updateTime=?, payBatchNo=? WHERE idBoardGameTable = ?`;
  dbConnect
    .prepare(updateSql, [
      1,
      nowDate.getTime(),
      nowDate.getTime(),
      payBatchNo,
      cardItem.idBoardGameTable,
    ])
    .run((err) => {
      if (err == null) {
        ElMessage({
          showClose: true,
          message: "开始计时",
          type: "success",
        });
      } else {
        ElMessage({
          showClose: true,
          message: "操作失败",
          type: "error",
        });
      }
      initData();
    });
}

function handleSettlement(cardItem) {
  if (cardItem.status != 1) {
    ElMessage({
      showClose: true,
      message: "该桌未启动计时，不能结算",
      type: "error",
    });
    return;
  }
  currentCardItem = cardItem;

  Promise.all([
    new Promise((resolve, reject) => {
      dbConnect.all(
        `select * from sales_record where type = 1 and payBatchNo = '${currentCardItem.payBatchNo}'`,
        (err, row) => {
          goodsSalesTableData.splice(0);
          goodsSalesTableData.push(...row);
          resolve(row);
        }
      );
    }),
  ]).then((result) => {
    feeDescriptions.beginTime = currentCardItem.lastBeginTime;
    feeDescriptions.totalTime = currentCardItem.totalTime;
    feeDescriptions.unitPrice = currentCardItem.unitPrice + " 元 / 时";
    feeDescriptions.cardPaidAmount = currentCardItem.totalFee;
    feeDescriptions.goodsPaidAmount = goodsSalesTableData
      .filter((obj) => obj.payStatus == "0")
      .reduce((a, curr) => a + curr.actuallyPaidAmount, 0);
    feeDescriptions.goodsUnPaidAmount = goodsSalesTableData
      .filter((obj) => obj.payStatus == "1")
      .reduce((a, curr) => a + curr.actuallyPaidAmount, 0);
    feeDescriptions.paidAmount = (
      parseFloat(feeDescriptions.cardPaidAmount) +
      parseFloat(feeDescriptions.goodsUnPaidAmount)
    ).toFixed(2);
    feeDescriptions.actuallyPaidAmount = parseFloat(feeDescriptions.paidAmount).toFixed(2);
    showJieSuabtn.value = true;
    drawer.value = true;
  });
}

function handleDetail(cardItem) {
  if (cardItem.status != 1) {
    ElMessage({
      showClose: true,
      message: "该桌未启动计时，不能打开详情页面",
      type: "error",
    });
    return;
  }
  currentCardItem = cardItem;
  Promise.all([
    new Promise((resolve, reject) => {
      dbConnect.all(
        `select * from sales_record where type = 1 and payBatchNo = '${currentCardItem.payBatchNo}'`,
        (err, row) => {
          goodsSalesTableData.splice(0);
          goodsSalesTableData.push(...row);
          resolve(row);
        }
      );
    }),
  ]).then((result) => {
    feeDescriptions.beginTime = currentCardItem.lastBeginTime;
    feeDescriptions.totalTime = currentCardItem.totalTime;
    feeDescriptions.unitPrice = currentCardItem.unitPrice + " 元 / 时";
    feeDescriptions.cardPaidAmount = currentCardItem.totalFee;
    feeDescriptions.goodsPaidAmount = goodsSalesTableData
      .filter((obj) => obj.payStatus == "0")
      .reduce((a, curr) => a + curr.actuallyPaidAmount, 0);
    feeDescriptions.goodsUnPaidAmount = goodsSalesTableData
      .filter((obj) => obj.payStatus == "1")
      .reduce((a, curr) => a + curr.actuallyPaidAmount, 0);
    feeDescriptions.paidAmount = (
      parseFloat(feeDescriptions.cardPaidAmount) +
      parseFloat(feeDescriptions.goodsUnPaidAmount)
    ).toFixed(2);
    feeDescriptions.actuallyPaidAmount = parseFloat(feeDescriptions.paidAmount).toFixed(2);
    showJieSuabtn.value = false;
    drawer.value = true;
  });
}

function handleAddGoods(cardItem) {
  if (cardItem.status != 1) {
    ElMessage({
      showClose: true,
      message: "该桌未启动计时，不能添加商品",
      type: "error",
    });
    return;
  }
  currentCardItem = cardItem
  dialogFormVisible.value = true;
}

function handleJieSuan() {
  ElMessageBox.confirm("是否完成结算", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
  }).then(() => {
    saveCardTableSales();
    ElMessage({
      showClose: true,
      message: "结算成功",
      type: "success",
    });
    initData();
    drawer.value = false;
  });
}
</script>


<style>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.box-card {
  width: 300px;
}
</style>
